import { CategoryEntity } from './entities/category.entity';
import { InjectRepository } from '@nestjs/typeorm';
import { Injectable,HttpStatus,Query } from '@nestjs/common';
import { Like, Repository } from 'typeorm';
import { HttpException } from '@nestjs/common/exceptions';
@Injectable()
export class CategoryService {
  constructor(
    @InjectRepository(CategoryEntity)
    private readonly categoryRepository: Repository<CategoryEntity>,
  ) {}

  async create(name: string) {
    return await this.categoryRepository.save({ name });
  }

  // async findById(id) {
  //   return await this.categoryRepository.findOne(id);
  // }

  async findById(id) {
    const result = await this.categoryRepository.findOne(id);;
    if (!result)
      throw new HttpException(`id为${id}的分类不存在`, HttpStatus.BAD_REQUEST);
    return result;
    }

  async findAll(query){
    const {pageNum = 1, pageSize = 10, ...params} = query;
    const result = await this.categoryRepository.findAndCount({
      where:query.name?{ name:Like(`%${query.name}%`)}:'true',
      order: {
        id: 'DESC',
      },
      skip: (pageNum - 1) * pageSize,
      take: pageSize,
    });
    const list = result[0].map((item) => item);
    return { list, count: result[1] };
  }
}
